package com.xh3140.xwidget.dialog.view;

import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.drawable.GradientDrawable;
import android.text.InputFilter;
import android.view.Gravity;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.xh3140.xwidget.dialog.params.InputParams;

/**
 * 输入主体视图
 */
public class InputView extends AppCompatEditText {

  public InputView(@NonNull Context context) {
    super(context);
    setFocusable(true);
    setFocusableInTouchMode(true);
    final LinearLayoutCompat.LayoutParams layoutParams = new LinearLayoutCompat.LayoutParams(
            LinearLayoutCompat.LayoutParams.MATCH_PARENT,
            LinearLayoutCompat.LayoutParams.WRAP_CONTENT, 1f);
    layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
    setLayoutParams(layoutParams);
  }

  /**
   * 配置视图
   *
   * @param params 输入主体视图配置属性
   */
  public InputView configView(@NonNull final InputParams params) {
    setInputType(params.inputType);
    setText(params.text);
    if (params.text != null) {
      setSelection(0, params.text.length());
    }
    setTextSize(params.textSize);
    setTextColor(params.textColor);
    setTypeface(getTypeface(), params.typeface);
    setHint(params.hint);
    setHintTextColor(params.hintColor);
    setGravity(params.gravity);
    setSingleLine(params.singleLine);
    if (params.maxLines > 0) {
      setMaxLines(params.maxLines);
    }
    setMaxEms(params.maxEms);
    if (params.maxLength > 0) {
      setFilters(new InputFilter[]{new InputFilter.LengthFilter(params.maxLength)});
    }
    if (params.backgroundResource != 0) {
      setBackgroundResource(params.backgroundResource);
    } else {
      final GradientDrawable background = new GradientDrawable();
      background.setColor(ColorStateList.valueOf(params.backgroundColor));
      background.setCornerRadius(params.radius);
      background.setStroke(params.strokeWidth, params.strokeColor);
      setBackground(background);
    }
    if (params.padding != null) {
      setPaddingRelative(params.padding[0], params.padding[1], params.padding[2], params.padding[3]);
    }
    if (params.margins != null) {
      final ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
      layoutParams.setMarginStart(params.margins[0]);
      layoutParams.topMargin = params.margins[1];
      layoutParams.setMarginEnd(params.margins[2]);
      layoutParams.bottomMargin = params.margins[3];
      setLayoutParams(layoutParams);
    }
    requestFocus();
    if (params.callback != null) {
      params.callback.callback(this);
    }
    return this;
  }
}
